import _ from 'underscore'
import $ from 'jquery'
import {Scope} from 'lib/scopeFactory'
import {coreApi,parseToChart} from '../apis/core-util'
import traceDetail from '../apis/traceDetail'
import TimeStore from 'lib/stores/time-store'
import crashNameFormat from '../apis/crashNameFormat'
// import {imsiApi,createGridOrder,parseToPartIMSIGrid} from '../apis/imsi-grid-util'
import {tracelistApi,createGridOrder,parseToPartGrid} from '../apis/tracelist'
import basicInfo from '../apis/basicInfo'
export default class MainScope extends Scope {
  constructor(props){
    super(props);
    this.crashtraceId = props.routeParams.crashtraceId;
    //this.uploadDataId = props.routeParams.uploadDataId;
    this.$state = {
      crashDetailProcessing: false,
      trace:null,
      affectedUser: -1,
      chart:{
        loading:true
      },
      pie0:{
        loading:true
      },
      pie1:{
        loading:true
      },
      detail:null,
      imsiGrid:{
        loading:true,
        getOrder:createGridOrder('timestamp',-1),
        fetch:this.fetchGrid.bind(this)
      },
      pieChartSettings: {
        legend: {
          layout: 'vertical',
          align: 'right',
          verticalAlign: 'middle',
          x: -50,
          navigation: {
            animation: true
          }
        },
        plotOptions: {
          pie: {
            dataLabels: {
              enabled: false
            },
            showInLegend: true
          }
        }
      }
    }
    this.traces = [];
    this.traceOffset = 0;
    this.modelApi = coreApi({
      urlName:BlueWare.platform.toLowerCase()+'_crash_series_data',
      classify:'crashname',
      order:'301',
      viewKey:'crash_count',
      crashNameId:this.crashtraceId
    },TimeStore.getValue)
    this.affectedUserApi = coreApi({
      urlName:BlueWare.platform.toLowerCase()+'_crash_series_data',
      classify:'crashname',
      order:'301',
      size: 1,
      viewKey:'crash_count',
      crashNameId:this.crashtraceId
    },TimeStore.getValue)
    this.pie0Api = coreApi({
      size:1,
      classify:BlueWare.isAndroid?'manufacturer':'model',
      urlName:BlueWare.platform.toLowerCase()+'_crash_series_data',
      viewKey:'crash_count',
      order:'303',
      crashNameId:this.crashtraceId
    },TimeStore.getValue);
    this.pie1Api = coreApi({
      size:1,
      classify:'osversion',
      urlName:BlueWare.platform.toLowerCase()+'_crash_series_data',
      viewKey:'crash_count',
      order:'303',
      crashNameId:this.crashtraceId
    },TimeStore.getValue);

    this.imsiApi = tracelistApi({
      urlName:'custom/affected_users',
      limit:10,
      // size:1,
      //uploadDataId:this.uploadDataId,
      crashNameId:this.crashtraceId,
      dataType:BlueWare.platform.toLowerCase()==='android'?1:2
      // order: 'appVersion', // appVersion, timestamp
      // orderModel: 'desc' // asc, desc
    },TimeStore.getValue,this.$state.imsiGrid.getOrder,function(){
      return {
        appVersionId:this.$state.trace?this.$state.trace.appVersionId:undefined
      }
    }.bind(this))

  }
  fetchGrid(){
    var _this = this
    this.imsiApi.fetch().then((rawData,params) => {
      _this.$state.imsiGrid = parseToPartGrid(rawData,params)
      // _this.$state.grid = parseToPartIMSIGrid(rawData.data,params)
      _this.emit()
    })
  }
  fetch(){
    var _this = this
    this.affectedUserApi
        .fetch()
        .done((data, params) => this.$state.affectedUser = data.result[0].combData.affected)
        .always(() => this.emit());

    this.modelApi.fetch().then(function(data,params){
      if(data.result.length){
        _this.$state.trace = _.extend({},data.result[0].key,
                data.result[0].combData,{name:crashNameFormat(data.result[0].key.name)})
        _this.showDetail()
      }else{
        _this.$state.trace = 0
      }
      _this.$state.chart = {
        data:parseToChart(data,params)
      }
      if (!_this.$state.chart.data.series[0].name) {
        let name = data.result && data.result.length && data.result[0].key &&data.result[0].key.name;
        if (name) {
          let index = name.indexOf('|')
            , filteredName = name.substring(0, index);

          _this.$state.chart.data.series[0].name = filteredName;
        }
      }
    },function(err){
      _this.$state.chart = {
        error:err
      }
    },function(params){
      _this.$state.chart = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(function(){
      _this.emit()
    })

    this.pie0Api.fetch().then(function(data,params){
      _this.$state.pie0 = {
        data:parseToChart(data,params)
      }
    },function(err){
      _this.$state.pie0 = {
        error:err
      }
    },function(params){
      _this.$state.pie0 = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(function(){
      _this.emit()
    })
    this.pie1Api.fetch().then(function(data,params){
      _this.$state.pie1 = {
        data:parseToChart(data,params)
      }
    },function(err){
      _this.$state.pie1 = {
        error:err
      }
    },function(params){
      _this.$state.pie1 = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(function(){
      _this.emit()
    })
  }
  genActivityUrl(activity){
    if(!this.activityNames){
      return 'javascript:;'
    }else{
      var matcher = _(this.activityNames).find((names) => names.name === activity.name)
      if(matcher){
        return BlueWare.pageUrlPrefix+'/app/'+BlueWare.appId+'/interaction#/measurementname/'+matcher.id
      }else{
        return 'javascript:;'
      }
    }
  }
  showDetail(offset){
    let previousOffset = this.traceOffset;
    var _this = this
    if(offset!==undefined){
      if(offset<0||offset>this.$state.trace.count - 1){
        return ;
      }
      this.traceOffset = offset;
    }
    if(this.traces[this.traceOffset]){
      this.$state.detail = this.traces[this.traceOffset];
      this.emit();
    }else{
      traceDetail({
        urlName: BlueWare.platform.toLowerCase() + '_crash_detail_data',
        crashNameId: this.crashtraceId,
        offset: this.traceOffset
      }, TimeStore.getValue)
        .fetch()
        .progress(() => {
          this.$state.crashDetailProcessing = true;
          this.emit();
        })
        .fail(() => {
          this.traceOffset = previousOffset;
        })
        .then(function (trace, params) {
          _this.traces[params.offset] = _.extend({}, trace, {
            name: crashNameFormat(trace.crashName),
            deviceInfo: trace.deviceInfo ? JSON.parse(trace.deviceInfo) : {},
            extraData: _.extend({}, trace.extraData, {
              datas: (trace.extraData && trace.extraData.datas) ? JSON.parse(trace.extraData.datas) : {}
            }),
            validPackageList: (trace.validPackageList || '').split(','),
            activityHistory: trace.activityHistory ? JSON.parse(trace.activityHistory).activityHistory : null,
            threads: JSON.parse(trace.threads),
            runningApps: trace.runningApps ? _.chain(JSON.parse(trace.runningApps)).filter(function (i) { return i.length }).map(function (i) {
              return {
                pid: i[0],
                name: i[1],
                packages: i[2] && i[2].split(','),
                mem: parseInt(i[3])
              }
            }).value() : []
          })
          _this.$state.detail = _this.traces[params.offset];
        })
        .always(() => {
          this.$state.crashDetailProcessing = false;
          _this.emit();
        });
    }
  }
  showIMSI(force){
    var _this = this
    if((force&&this.$state.imsiGrid.data)||(!force&&!this.$state.imsiGrid.data)){
      this.imsiApi.fetch().then((rawData,params) => {
        // _this.$state.imsiGrid = parseToPartIMSIGrid(_.map(rawData.data, item => {
        _this.$state.imsiGrid = parseToPartGrid(_.map(rawData, item => {
          item.crashNameId = _this.crashtraceId;
          return item
        }),params, p => {
            _.map(p, i => {
              i['crashNameId'] = _this.crashtraceId;
              return i;
            })
          })
        _this.$state.imsiGrid.getOrder=createGridOrder('timestamp',-1);
        _this.$state.imsiGrid.fetch=this.showIMSI.bind(this);
        _this.emit()
      })
    }
  }
  toggleState(key){
    var params = {
      crashNameId:this.crashtraceId,
      appVersionId:this.$state.trace.appVersionId,
      csrf_token:BlueWare.CSRFTOKEN
    }

    if(key === 'fix') {
      this.$state.trace.fixed = !this.$state.trace.fixed;
      params.fix = this.$state.trace.fixed;
    }
    else {
      this.$state.trace[key] = !this.$state.trace[key];
      params[key] = this.$state.trace[key]
    }
    $.ajax({
      url:BlueWare.urlPrefix + '/app/' + BlueWare.appId + '/mark_ios_crash_reason.json',
      type:'post',
      data:params
    }).done(() => {
      this.emit()
    })
  }
  $settime(payload){
    this.fetch()
    this.showIMSI(true)
  }
  $load(){
    this.fetch();
    basicInfo({
      urlName:'interaction'
    }).fetch().then((info) => {
      this.activityNames = info.result.map((i) => ({
        id:i.id,
        name:i.name.substring(_.lastIndexOf(i.name,'/')+1)
      }))
    })
  }
}
